import 'dart:async';
import 'dart:typed_data';

import 'package:charset_converter/charset_converter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shen_nai/app/user_controller.dart';
import 'package:shen_nai/entity/device_entity.dart';
import 'package:shen_nai/eventbus/event_bus.dart';
import 'package:shen_nai/pages/main/page/home/components/device_item_view.dart';
import 'package:shen_nai/socket/socket_server_manage.dart';

//首页
class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  //监听当前设备信息
  StreamSubscription? _subscription;

  @override
  void initState() {
    super.initState();
    getDevicesList();
    _subscription =
        eventBus.on<UpdateQualityGuaranteeSuccess>().listen((event) {
      for (var item in _list) {
        if (item.ID == event.deviceEntity.ID) {
          item.qualityDate = event.deviceEntity.qualityDate;
          item.qualityDays = event.deviceEntity.qualityDays;
          item.qualityIsBuy = event.deviceEntity.qualityIsBuy;
          break;
        }
      }
      for (var item in _dataList) {
        if (item.ID == event.deviceEntity.ID) {
          item.qualityDate = event.deviceEntity.qualityDate;
          item.qualityDays = event.deviceEntity.qualityDays;
          item.qualityIsBuy = event.deviceEntity.qualityIsBuy;
          setState(() {
            _dataList;
          });
          break;
        }
      }
    });
  }

  @override
  void dispose() {
    _subscription?.cancel();
    super.dispose();
  }

  final List<DeviceEntity> _list = [];
  final List<DeviceEntity> _dataList = [];

  //根据用户查询设备
  getDevicesList() {
    String query = (Get.find<UserController>().jurisdiction < 2 ||
            Get.find<UserController>().jurisdiction == 10)
        ? "query devicesmb all"
        : "query devicesmb users ${Get.find<UserController>().account}";
    SocketServerManage().writeData(query, (Uint8List data) async {
      int firstIndex = 0;
      int basicLength = 16;
      while (true) {
        var sub;
        if (data.length >= firstIndex + basicLength) {
          sub = data.sublist(firstIndex, firstIndex + basicLength);
        } else {
          break;
        }

        var substring = String.fromCharCodes(sub);
        if (substring.contains('over')) {
          _dataList.addAll(_list);
          setState(() {
            _dataList;
          });
          break;
        }
        var split = substring.split(' ');
        int length = int.parse(split[split.length - 1]);
        var value = await CharsetConverter.decode(
            'GBK',
            data.sublist(
                basicLength + firstIndex, length + firstIndex + basicLength));
        var subValue = value.split(' ');
        String power2 = '0';
        String time2 = '0';
        if (int.parse(subValue[24]) >= 2) {
          power2 = subValue[30];
          time2 = subValue[31];
        }
        _list.add(DeviceEntity(
            int.parse(subValue[2]),
            subValue[3],
            subValue[4],
            subValue[5],
            subValue[6],
            subValue[7],
            int.parse(subValue[8]),
            subValue[9],
            subValue[10],
            subValue[11],
            subValue[12],
            subValue[13],
            subValue[14],
            subValue[15],
            subValue[16],
            subValue[17],
            subValue[18],
            subValue[19],
            subValue[20],
            subValue[21],
            subValue[22],
            subValue[23],
            subValue[24],
            subValue[25],
            subValue[26],
            subValue[27],
            subValue[28],
            subValue[29],
            power2,
            time2));
        firstIndex += (length + basicLength);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Container(
              alignment: Alignment.centerLeft,
              // color: Colors.white,
              margin: EdgeInsets.only(
                  top: MediaQuery.of(context).padding.top + 24,
                  left: 16,
                  right: 16,
                  bottom: 8),
              child: Row(
                children: [
                  Expanded(
                    child: Text(
                      Get.find<UserController>().username,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(color: Colors.white, fontSize: 16),
                    ),
                  ),
                  TextButton(
                      onPressed: () {
                        _showSelectAreaDialog();
                      },
                      style: TextButton.styleFrom(
                          minimumSize: const Size(0, 0),
                          padding: const EdgeInsets.symmetric(
                              horizontal: 5, vertical: 2)),
                      child: Text('选择地区'))
                ],
              )),
          Expanded(
              child: MediaQuery.removePadding(
                  removeTop: true,
                  context: context,
                  child: ListView.builder(
                    itemBuilder: (BuildContext context, int index) {
                      return DeviceItemView(_dataList[index]);
                    },
                    itemCount: _dataList.length,
                  )))
        ],
      ),
    );
  }

  //选择地区
  _showSelectAreaDialog() {
    Set<String> areaSet = {};
    areaSet.add('全部');
    _list.forEach((element) {
      areaSet.add(element.area!);
    });
    Set<String> companySet = {};
    companySet.add('全部');
    String area = '全部';
    String company = '全部';
    Get.bottomSheet(StatefulBuilder(builder: (context, setSheetstate) {
      return SizedBox(
        height: 240,
        child: Column(
          children: [
            Row(
              children: [
                TextButton(
                    onPressed: () {
                      Get.back();
                    },
                    child: const Text(
                      '取消',
                      style: TextStyle(color: Colors.blue, fontSize: 16),
                    )),
                const Expanded(
                    child: Text(
                  '请选择',
                  style: TextStyle(fontSize: 16),
                  textAlign: TextAlign.center,
                )),
                TextButton(
                    onPressed: () {
                      Get.back();
                      _dataList.clear();
                      if (area == '全部') {
                        _dataList.addAll(_list);
                      } else {
                        if (company == '全部') {
                          _dataList.addAll(
                              _list.where((element) => element.area == area));
                        } else {
                          _dataList.addAll(_list
                              .where((element) => element.area == area)
                              .where((element) => element.name == company));
                        }
                      }
                      setState(() {
                        _dataList;
                      });
                    },
                    child: const Text(
                      '确定',
                      style: TextStyle(color: Colors.blue, fontSize: 16),
                    ))
              ],
            ),
            Expanded(
                child: Row(
              children: [
                Expanded(
                    flex: 1,
                    child: CupertinoPicker(
                      itemExtent: 40,
                      onSelectedItemChanged: (index) {
                        area = areaSet.elementAt(index);
                        companySet.clear();
                        if (area == '全部') {
                          companySet.add('全部');
                        } else {
                          companySet.add('全部');
                          companySet.addAll(_list
                              .where((element) => area == element.area)
                              .map((e) => e.name!));
                        }
                        setSheetstate(() {
                          companySet;
                        });
                      },
                      children: areaSet.map((data) {
                        return Center(
                          child: Text(
                            data,
                            style: const TextStyle(fontSize: 14),
                          ),
                        );
                      }).toList(),
                    )),
                Expanded(
                    flex: 2,
                    child: CupertinoPicker(
                      itemExtent: 40,
                      onSelectedItemChanged: (index) {
                        //value = _selectList[index];
                        company = companySet.elementAt(index);
                      },
                      children: companySet.map((data) {
                        return Center(
                          child: Text(
                            data,
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                            style: const TextStyle(fontSize: 14),
                          ),
                        );
                      }).toList(),
                    ))
              ],
            ))
          ],
        ),
      );
    }),
        backgroundColor: Colors.white,
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(15))));
  }
}
